﻿using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ShortUrl.WebUI.Codes;
using ShortUrl.WebUI.Codes.Algorithm;
using ShortUrl.WebUI.Models;

namespace ShortUrl.WebUI.Controllers
{
    public class UrlController : Controller
    {
        [HttpPost]
        public ActionResult Create(string urlLong)
        {
            var context = new ShortUrlContext();

            var shortKey = ShorUrlCalc.ShortUrl(urlLong)[0];
            var model = context.UrlLinks.SingleOrDefault(x => x.ShortKey == shortKey);
           
            if (model != null)
                return Json(new JsonResultContent { statusCode = 0, url = Config.RootUrl + model.ShortKey, message = "" });

            model = new UrlLink()
            {
                CreatedDate = DateTime.Now,
                ShortKey = ShorUrlCalc.ShortUrl(urlLong)[0],
                UrlLong = urlLong
            };

            try
            {
                context.UrlLinks.Add(model);
                context.SaveChanges();
            }
            catch (Exception ex)
            {
                return Json(new JsonResultContent { statusCode = 1, url = "", message = ex.Message });
            }

            return Json(new JsonResultContent { statusCode = 0, url = Config.RootUrl + model.ShortKey });
        }

        [HttpGet]
        public ActionResult Index(string id)
        {
            UrlLink model;
            using (var context = new ShortUrlContext())
            {
                model = context.UrlLinks.SingleOrDefault(s => s.ShortKey == id);
                if (model != null)
                {
                    model.VisitCount += 1;
                    context.SaveChanges();
                }
            }

            if (model == null)
            {
#if DEBUG
                return Content("Error");
#else
                return Redirect("http://www.qiulianwang.com");
#endif            
            }
            else
                return Redirect(model.UrlLong);
        }
    }
}